/*
 *  Copyright (C) 2011 glauco
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.balisunrise.nbpam.components;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.swing.JPanel;
import org.balisunrise.application.Module;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.util.ImageUtilities;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.balisunrise.nbpam.components//ModuleMenu//EN",
autostore = false)
public final class ModuleMenuTopComponent extends TopComponent {

    private static ModuleMenuTopComponent instance;
    private static Module module;
    private static Map<String, ModuleMenuPanel>
            panels = new HashMap<String, ModuleMenuPanel>();
    private static final String PREFERRED_ID = "ModuleMenuTopComponent";

    private String icon;

    public ModuleMenuTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(ModuleMenuTopComponent.class,
                "CTL_ModuleMenuTopComponent"));
        setToolTipText(NbBundle.getMessage(ModuleMenuTopComponent.class,
                "HINT_ModuleMenuTopComponent"));
        initProps();
    }

    public ModuleMenuTopComponent(Module module){
        setProps(module);
        initProps();
    }
    
    private void initProps(){
        if (icon != null)
            setIcon(ImageUtilities.loadImage(icon));
        putClientProperty(TopComponent.PROP_DRAGGING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
    }

    private void setProps(Module module) {
        ModuleMenuTopComponent.module = module;
        setName(module.getDescription());
        setToolTipText(module.getToolTipText());
        icon = module.getSmallIcon();
        init();
    }

    private void init(){

        removeAll();
        
        JPanel panel = getModulePanel(module);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setPreferredSize(new java.awt.Dimension(280, 300));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 280, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 440, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized ModuleMenuTopComponent getDefault() {
        if (instance == null) {
            instance = new ModuleMenuTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the ModuleMenuTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ModuleMenuTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(ModuleMenuTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ModuleMenuTopComponent) {
            return (ModuleMenuTopComponent) win;
        }
        Logger.getLogger(ModuleMenuTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    /**
     * Obtem a instância do ModuleMenuTopComponet do Module específico.
     * Nunca chame {@link #getDefault()} ou {@link #findInstace()}.
     * @param m Modulo do ModuleMenuTopComponent.
     */
    public static synchronized ModuleMenuTopComponent findInstance(Module m){
        ModuleMenuTopComponent tc = findInstance();
        tc.setProps(m);
        return tc;
    }

    public static synchronized ModuleMenuPanel getModulePanel(Module module){
        ModuleMenuPanel panel;
        if(module == null)
            panel = new ModuleMenuPanel();
        else if(panels.containsKey(module.getName())){
            panel = panels.get(module.getName());
        }else{
            panel = new ModuleMenuPanel(module);
            panels.put(module.getName(),panel);
        }
        return panel;
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        // add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        p.setProperty("version", "1.0");
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }
}
